﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Reflection;
using System.Threading;
using Fares.DataSets;


namespace Fares
{
    public partial class PlatiFrm : FrmWorkspace
    {
        private Dictionary<String, String> SeriiNumerice = new Dictionary<string, string>();
        public int LunaCurenta = 1;
        public int AnulCurent = 2000;
        public Boolean ParteneriProprii = true;
        public Boolean Bugetara = false;
        /// <summary>
        /// numarul de inregistrari adaugate
        /// </summary>
        private Int32 NoRecAdd = 0;
        private Boolean AddNewPay = false;
        private Int64 IdPartener = -1;
        private DateTime DataPlata = DateTime.MinValue;
        private Decimal Valoare = Decimal.Zero;
        private Decimal ValoareTVA = Decimal.Zero;
        private Int64 IDDocument = -1;
        DataSets.ESRPDataSetPlati.FaresSetupRow FSRow = null;
        private String TipOperatiune = "O";

        public PlatiFrm(ModuleClass mc, Boolean adauga,Int64 idPart,DateTime dt,Decimal val,Decimal valTVA,Int64 iddoc,String tipOp):this(mc)
        {
            AddNewPay = adauga;
            IdPartener = idPart;
            DataPlata = dt;
            Valoare = val;
            ValoareTVA = valTVA;
            IDDocument = iddoc;
            TipOperatiune = tipOp;
        }

        public PlatiFrm(ModuleClass mc):base(mc)
        {
            InitializeComponent();
            AddOnlyMaster = true;
            workConnString = mc.workConnectionString;
            esrpDataSetPlati.DocumentePlata.TipOperatiuneColumn.DefaultValue = "I";
            esrpDataSetPlati.DocumentePlata.IDTipPlataColumn.DefaultValue = 5; //chitanta
            esrpDataSetPlati.DocumentePlata.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            esrpDataSetPlati.DocumentePlata.ValoareTotalaColumn.DefaultValue = 0;
            esrpDataSetPlati.DocumentePlata.ValoareTotalaTVAColumn.DefaultValue = 0;

            esrpDataSetPlati.DocumentePlataDetaliu.ValoareColumn.DefaultValue = 0;
            esrpDataSetPlati.DocumentePlataDetaliu.ValoareTVAColumn.DefaultValue = 0;


            tipOperatiunePlataBindingSource.Add(new TipOperatiunePlata("Incasare", "O"));
            tipOperatiunePlataBindingSource.Add(new TipOperatiunePlata("Plata", "I"));

            documentePlataTableAdapter.Adapter.RowUpdated += new SqlRowUpdatedEventHandler(Adapter_RowUpdated);
            documentePlataTableAdapter.Adapter.RowUpdating += new SqlRowUpdatingEventHandler(Adapter_RowUpdating);
            this.HandleAfterAdd += new AfterAddHandler(HandleAfterAddDocPlata);
            this.HandleBeforeDelAfterMessage += PlatiFrm_HandleBeforeDelAfterMessage;
            HandleRezumat += new EventHandler(PlatiFrm_HandleRezumat);
            this.HandleTiparire += new EventHandler(Tiparire);


            lstPK.Add(numarTB);
            nrDataDocColumn.DataSource = faresGenereazaDocumentePentruPlataBindingSource;
            nrDataDocColumn.DisplayMember = "NrDataDoc";
            nrDataDocColumn.ValueMember = "IDDocument";
            ActiveControl = denumireCB;
            EnableMainBrowseButton = true;

            this.documentePlataDetaliuTableAdapter.SetTableName(ModuleInfo.AnArhiva);
            this.documentePlataTableAdapter.SetTableName(ModuleInfo.AnArhiva);
            if (ModuleInfo.AnArhiva != String.Empty)
                ReadOnly = true;

            
        }

        bool PlatiFrm_HandleBeforeDelAfterMessage(object sender, EventArgs args, bool Detaliu)
        {
            if (Detaliu || !Bugetara)
                return true;

            for (int i = 0; i < ordonantariBindingSource.Count; i++)
            {
                if (ordonantariBindingSource.Count != 0)
                {
                    foreach (DataRowView dl in ordonantariBindingSource)
                    {
                        ordonantariBindingSource.Remove(dl);
                    }
                }
            }
            return true;
        }

        void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs args)
        {
            if (args.StatementType == StatementType.Delete)
                return;
            String serie = SeriiNumerice["CHIT"];
            if (Convert.ToInt32(args.Row["IDTipPlata"]) != 5)
                serie = SeriiNumerice["PLATI"];
            ///doar pentru chitanta
            if (args.StatementType != StatementType.Insert || serie == String.Empty || args.Row["TipOperatiune"].ToString()!="O")
                return;
            SqlDataAdapter da = sender as SqlDataAdapter;
            //Seteaza seria numerica
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("", con);
            
            cmd.CommandText = "SELECT [Serie] FROM [SeriiNumerice] WHERE IDSerie='" + serie + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                da.InsertCommand.Parameters["@Serie"].Value = ret.ToString();
            }
            cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + serie + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                da.InsertCommand.Parameters["@Numar"].Value = ret.ToString();
            }

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "ActSeriiNumerice";
            cmd.Parameters.Add(new SqlParameter("IDSerie", serie));
            cmd.Parameters.Add(new SqlParameter("CodUnitate", ModuleInfo.CodUnitate));
            cmd.ExecuteNonQuery();
            InchideConexiune(con);

        }

        void PlatiFrm_HandleRezumat(object sender, EventArgs e)
        {
            Int32 selID = -1;
            if (documentePlataBindingSource.Current != null)
            {
                DataSets.ESRPDataSetPlati.DocumentePlataRow prr = ((DataRowView)documentePlataBindingSource.Current).Row as DataSets.ESRPDataSetPlati.DocumentePlataRow;
                selID = (Int32)prr.IDDocumentPlata;
            }
            PlatiRezumatFrm frm = new PlatiRezumatFrm(ModuleInfo, documentePlataBindingSource, documentePlataDetaliuBindingSource,selID);
            frm.SelectionAddOn = true;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (frm.selectedDataRow != null)
                {
                    documentePlataBindingSource.RemoveFilter();
                    DataSets.ESRPDataSetPlati.DocumentePlataRow pr = frm.selectedDataRow.Row as DataSets.ESRPDataSetPlati.DocumentePlataRow;
                    documentePlataBindingSource.Position = documentePlataBindingSource.Find("IDDocumentPlata", pr.IDDocumentPlata);
                }
            }
            EnableMainBrowseButton = true;
        }

        private void PlatiFrm_Load(object sender, EventArgs e)
        {
           
            EnableMainBrowseButton = true;
            EnableMainSearchButton = true;
            AddButton("Facturi", global::ERPStudio.Properties.Resources.folder, Facturi, ToolStripItemAlignment.Right, true);

            SqlConnection con = DeschideConexiune(workConnString);
            Setup(con);
            this.ordonantariTableAdapter.Connection = con;
            this.ordonantariTableAdapter.Fill(this.esrpDataSetPlati.Ordonantari,ModuleInfo.CodUnitate);

            this.fares_ParteneriCUITableAdapter.Connection = con;
            if(ParteneriProprii)
                this.fares_ParteneriCUITableAdapter.FillByUnitate(this.esrpDataSetPlati.fares_ParteneriCUI, ModuleInfo.CodUnitate);
            else
                this.fares_ParteneriCUITableAdapter.Fill(this.esrpDataSetPlati.fares_ParteneriCUI);

            this.tipDocumentPlataTableAdapter.Connection = con;
            this.tipDocumentPlataTableAdapter.Fill(this.esrpDataSetPlati.TipDocumentPlata);
            
            this.documentePlataTableAdapter.Connection = con;
            if (AddNewPay)
                this.documentePlataTableAdapter.FillByIDDocument(this.esrpDataSetPlati.DocumentePlata,IDDocument);
            else
                this.documentePlataTableAdapter.Fill(this.esrpDataSetPlati.DocumentePlata, ModuleInfo.CodUnitate);

            this.documentePlataDetaliuTableAdapter.Connection = con;
            this.documentePlataDetaliuTableAdapter.Fill(this.esrpDataSetPlati.DocumentePlataDetaliu);
            

            

            AddBindingSource(documentePlataBindingSource);
            AddBindingSource(documentePlataDetaliuBindingSource);
            AddBindingSource(ordonantariBindingSource);
            listTableAdaptor.Add(documentePlataTableAdapter.Adapter);
            listTableAdaptor.Add(documentePlataDetaliuTableAdapter.Adapter);
            listTableAdaptor.Add(ordonantariTableAdapter.Adapter);

            tipOperatiuneCB_SelectedIndexChanged(denumireCB, null);
            if (documentePlataBindingSource.Count == 0)
            {
                Adauga(this, null);
               if (AddNewPay)
                {
                    DataSets.ESRPDataSetPlati.DocumentePlataRow dpr = ((DataRowView)documentePlataBindingSource.Current).Row as DataSets.ESRPDataSetPlati.DocumentePlataRow;
                    dpr.IDPartener = IdPartener;
                    dpr.TipOperatiune = TipOperatiune;
                    dpr.Data = DataPlata;
                    denumireCB.SelectedValue = IdPartener;
                    tipOperatiuneCB.SelectedValue = TipOperatiune;
                    dataDTP.Value = DataPlata;
                    dpr.ValoareTotala = Valoare;
                    dpr.ValoareTotalaTVA = ValoareTVA;
                    dpr.EndEdit();

                    DataSets.ESRPDataSetPlati.DocumentePlataDetaliuRow dpdr = ((DataRowView)documentePlataDetaliuBindingSource.AddNew()).Row as DataSets.ESRPDataSetPlati.DocumentePlataDetaliuRow;
                    dpdr.Valoare = Valoare;
                    dpdr.ValoareTVA = ValoareTVA;
                    dpdr.IDDocument = IDDocument;
                    dpdr.IDDocumentPlata = dpr.IDDocumentPlata;
                    documentePlataDetaliuBindingSource.EndEdit();

                }
            }
            InchideConexiune(con);
            if (!ReadOnly)
            {
                HandleSalvare += Salvare;
            }
            else
                EnableLocalSaveButton = false;

            if (Bugetara)
            {
                AddButton("Ordonantare", global::ERPStudio.Properties.Resources.wallet, Generare_Ordonantare, ToolStripItemAlignment.Right, true);
                
                

            }

        }

        private void Generare_Ordonantare(object sender, EventArgs e)
        {
            Salvare();
            if (EroareSalvare)
                return;
            if (documentePlataBindingSource.Current == null)
                return;
            DataSets.ESRPDataSetPlati.DocumentePlataRow parr = ((DataRowView)documentePlataBindingSource.Current).Row as ESRPDataSetPlati.DocumentePlataRow;
            //genereaza ordonantarea in baza de date
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "GenOrdonantariPlata";
            cmd.Parameters.Add(new SqlParameter("idPlata", parr.IDDocumentPlata));
            cmd.Parameters.Add(new SqlParameter("idOrdonantare", 0));
            cmd.Parameters["idOrdonantare"].Direction = ParameterDirection.Output;
            cmd.Parameters["idOrdonantare"].DbType = DbType.Int32;
            cmd.Parameters["idOrdonantare"].IsNullable = false;
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch(Exception Ex)
            {
                InchideConexiune(con);
                MessageBoxFrm mbt = new MessageBoxFrm("Eroare", Ex.Message, String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.ShowDialog();
                return;
            }
            InchideConexiune(con);

            //MessageBox.Show(cmd.Parameters["idOrdonantare"].Value.ToString());
            FrmMainMdi frm = ModuleInfo.mdiForm as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;

            String numeClasa = "ExBug.OrdonantariFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                Int32 idOrdonatare = -1;
                if (cmd.Parameters["idOrdonantare"].Value != DBNull.Value)
                    idOrdonatare = Convert.ToInt32(cmd.Parameters["idOrdonantare"].Value);
                else
                {
                    MessageBox.Show("");
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Nu s-a generat ordonanţare, din cauza unei erori de sistem! Vă rugăm contactaţi producatorul aplicaţiei!", String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                    mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    return;
                }

                FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo, idOrdonatare }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;
                if (newFrm != null)
                {
                    //newFrm.MdiParent = frm;
                    newFrm.ShowDialog();
                    ordonantariTableAdapter.Connection = DeschideConexiune(workConnString);
                    ordonantariTableAdapter.Fill(esrpDataSetPlati.Ordonantari, ModuleInfo.CodUnitate);
                    InchideConexiune(ordonantariTableAdapter.Connection);
                }
            }

        }

        private void tipOperatiuneCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tipOperatiuneCB.SelectedValue == null || documentePlataBindingSource.Current == null)
                return;
            DataRowView drv = documentePlataBindingSource.Current as DataRowView;
            ESRPDataSetPlati.DocumentePlataRow dpr = drv.Row as ESRPDataSetPlati.DocumentePlataRow;
            if (tipOperatiuneCB.SelectedValue.ToString() == "O")
            {
                if (drv.IsNew)
                {
                    String serie = SeriiNumerice["CHIT"];
                    if (dpr.IDTipPlata != 5)
                        serie = SeriiNumerice["PLATI"];
                    if (serie != String.Empty && this.numarTB.Text == String.Empty)
                        this.numarTB.Text = NewNumberSerie(serie, dpr.IDTipPlata);
                }
            }

            if (denumireCB.SelectedItem == null )
                return;

            ESRPDataSetPlati.fares_ParteneriCUIRow parr = ((DataRowView)denumireCB.SelectedItem).Row as ESRPDataSetPlati.fares_ParteneriCUIRow;
            if (parr != null)
            {
                SqlConnection con = DeschideConexiune(workConnString);
                fares_GenereazaDocumentePentruPlataTableAdapter.Connection = con;
                fares_GenereazaDocumentePentruPlataTableAdapter.Fill(esrpDataSetPlati.fares_GenereazaDocumentePentruPlata,
                    ModuleInfo.CodUnitate, parr.IDPartener, tipOperatiuneCB.SelectedValue.ToString(),dpr.IDDocumentPlata, ModuleInfo.AnArhiva);
                InchideConexiune(con);
                
                if (drv.IsNew)
                    faresGenereazaDocumentePentruPlataBindingSource.Filter = "(RestPlata<>0) OR (NrDataDoc='AVANS')";
                else
                    faresGenereazaDocumentePentruPlataBindingSource.Filter = String.Empty;
            }
            else
                MessageBox.Show("Atentie!");

        }

        override public void Salvare(object sender, EventArgs args)
        {
            if (documentePlataBindingSource.Current != null)
            {
                if (numarTB.Text.Trim() == String.Empty)
                {
                    MessageBox.Show("Va rugam completati numarul incasarii/platii!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            this.SuspendLayout();
            docPlataDetaliuDGV.Enabled = false;

            base.Salvare(this, args);
            docPlataDetaliuDGV.Enabled = true;
            ResumeLayout();


            if (EroareSalvare)
                return;
            
            ///calculeaza totalul pentru cazul in care se sterge o linie
            ///
            SeteazaTotalDocument();
            tipOperatiuneCB_SelectedIndexChanged(denumireCB, null);
            docPlataDetaliuDGV.InvalidateColumn(nrDataDocColumn.Index);
        }

        private void Setup(SqlConnection wConn)
        {

            this.faresSetupTableAdapter.Connection = wConn;
            this.faresSetupTableAdapter.Fill(this.esrpDataSetPlati.FaresSetup, ModuleInfo.CodUnitate);

            while (faresSetupBindingSource.Count==0)
            {
                MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
                frm.ShowDialog();
                this.faresSetupTableAdapter.Fill(this.esrpDataSetPlati.FaresSetup,ModuleInfo.CodUnitate);
            }

            #region Setare data in format romanesc
            ///data in format romanesc
            ///
            dataDTP.Format = DateTimePickerFormat.Custom;
            dataDTP.CustomFormat = "dd.MM.yyyy";
            dataExtrasDTP.Format = DateTimePickerFormat.Custom;
            dataExtrasDTP.CustomFormat = "dd.MM.yyyy";

            #endregion

            FSRow = ((DataRowView)faresSetupBindingSource.Current).Row as ESRPDataSetPlati.FaresSetupRow;
            if (FSRow == null)
            {
                MessageBox.Show("Eroare citire configuratie modul. \nVa rugam sa-l configurati!",
                        "Eroare",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Hand);
                return;
            }

            #region Setare Serii Numerice
            SeriiNumerice.Add("PLATI", FSRow.IDSeriePlati);
            if(!FSRow.IsIDSerieCHITNull())
                SeriiNumerice.Add("CHIT", FSRow.IDSerieCHIT);
            else
                SeriiNumerice.Add("CHIT", String.Empty); 
            #endregion

            LunaCurenta = FSRow.LunaCurenta;

            AnulCurent = FSRow.AnCurent;

            ParteneriProprii = FSRow.ParteneriProprii;

            Bugetara = FSRow.Bugetara;


            DateTime inceputLuna = new DateTime(AnulCurent, LunaCurenta, 1);
            DateTime sfarsitLuna = inceputLuna.AddMonths(1).AddDays(-1);
            dataDTP.Value = sfarsitLuna;
            esrpDataSetPlati.DocumentePlata.DataColumn.DefaultValue = sfarsitLuna;
            esrpDataSetPlati.DocumentePlata.DataExtrasColumn.DefaultValue =sfarsitLuna;


            #region Setari TVA la incasare
            TVADocumentColumn.Visible = FSRow.PermiteTVALaIncasare;
            RestPlataTVAColumn.Visible = FSRow.PermiteTVALaIncasare;
            AchitatTVAColumn.Visible = FSRow.PermiteTVALaIncasare;
            totalTVATB.Visible = FSRow.PermiteTVALaIncasare;
            TotalTVAL.Visible = FSRow.PermiteTVALaIncasare;
            
            #endregion
            if (LunaCurenta == 0)
            {
                MessageBox.Show("Modulul Parteneri nu a fost configurat corect (Luna curenta=0). \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                return;
            }

            ///daca este in perioada curenta
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                //documenteBindingSource.Filter = "[DataDoc] <= '" + dataDocDTP.MaxDate.Year.ToString() + "-" + dataDocDTP.MaxDate.Month.ToString() + "-" + dataDocDTP.MaxDate.Day.ToString() + "'";
                //dataDocDTP.MaxDate = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
                //esrpDataSetPlati.Documente.DataDocColumn.DefaultValue = dataDocDTP.MaxDate;
                //SetInfoLunaAnul(LunaCurenta.ToString() + "," + AnulCurent.ToString());
            }
        }

        void Adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs args)
        {
            if (args.Errors != null)
                throw args.Errors;
            if (args.StatementType == StatementType.Insert)
            {
                foreach (DataRow row in
                    esrpDataSetPlati.DocumentePlataDetaliu.Select("IDDocumentPlata=" + args.Row["IDDocumentPlata", DataRowVersion.Original].ToString(),
                        "IDDocumentPlata", DataViewRowState.Added))
                {
                    row["IDDocumentPlata"] = args.Row["IDDocumentPlata"];
                }
            }
        }

        void HandleAfterAddDocPlata(object sender, DataGridViewCellEventArgs args)
        {
            if (documentePlataBindingSource.Current != null)
            {
                DataRowView drv = documentePlataBindingSource.Current as DataRowView;
                ESRPDataSetPlati.DocumentePlataRow dpr = ((DataRowView)documentePlataBindingSource.Current).Row as ESRPDataSetPlati.DocumentePlataRow;
                if (dpr.TipOperatiune == "O")
                {

                    String serie = SeriiNumerice["CHIT"];
                    if (dpr.IDTipPlata != 5)
                        serie = SeriiNumerice["PLATI"];
                    if (serie != String.Empty)
                    {
                        if (drv.IsNew && this.numarTB.Text==String.Empty)
                            this.numarTB.Text = NewNumberSerie(serie,dpr.IDTipPlata);
                    }
                }

            }

            //docDetaliuDGV[IDArticolColumn.Index, args.RowIndex].Value = String.Empty;
            ActiveControl =denumireCB;
            //sterge toate liniile din documentele care urmeaza sa fie platite
            esrpDataSetPlati.fares_GenereazaDocumentePentruPlata.Rows.Clear();
        }

        private String NewNumberSerie(String serie, short _IDTipPlata)
        {
            String valnew = "1";
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [UltimulNrFolosit] FROM [SeriiNumerice] WHERE IDSerie='" + serie + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                valnew = ret.ToString();
            }
            int cate = 0;
            DataRow[] dtr = esrpDataSetPlati.DocumentePlata.Select("TipOperatiune='O' AND IDTipPlata=" + _IDTipPlata.ToString(),
            "IDTipPlata", DataViewRowState.Added);
            if (dtr != null)
                cate = dtr.Length;
            Decimal valnum = Convert.ToDecimal(valnew);

            ///incrementarea seriei se face la salvare
            ///
            InchideConexiune(cmd.Connection);
            return (valnum + cate).ToString();
        }

        void SeteazaTotalDocument()
        {
            Decimal newValTVA, newVal = GetSum(ValoareColumn.Index, -1, docPlataDetaliuDGV, out newValTVA);
            Decimal valTB = Decimal.Zero;
            if (totalTB.Text!=String.Empty)
                valTB = Convert.ToDecimal(totalTB.Text);
            if (valTB != newVal + newValTVA)
                totalTB.Text = (newVal + newValTVA).ToString("N2");
            
            newVal = GetSum(ValoareTVAColumn.Index, -1, docPlataDetaliuDGV, out newValTVA);
            valTB = Decimal.Zero;
            if (totalTVATB.Text != String.Empty)
                valTB = Convert.ToDecimal(totalTVATB.Text);
            if (valTB != newVal + newValTVA)
                totalTVATB.Text = Math.Round(newVal + newValTVA, 2).ToString("N2");
        }

        private Decimal GetSum(int indexColoana, int idxColTVA, DataGridView DGV, out Decimal valTVA)
        {
            Decimal total = Decimal.Zero;
            valTVA = Decimal.Zero;
            foreach (DataGridViewRow dr in DGV.Rows)
            {
                if (dr.Cells[indexColoana].Value != DBNull.Value)
                {
                    if (dr.Cells[indexColoana].IsInEditMode)
                        total += Convert.ToDecimal(dr.Cells[indexColoana].EditedFormattedValue);
                    else
                        total += Convert.ToDecimal(dr.Cells[indexColoana].Value);
                }
                if (idxColTVA!=-1 && dr.Cells[idxColTVA].Value != DBNull.Value)
                {
                    if (dr.Cells[idxColTVA].IsInEditMode)
                    {
                        if (dr.Cells[idxColTVA].EditedFormattedValue.ToString().Trim() != String.Empty)
                            valTVA += Convert.ToDecimal(dr.Cells[idxColTVA].EditedFormattedValue);
                    }
                    else
                        valTVA += Convert.ToDecimal(dr.Cells[idxColTVA].Value);
                }
            }
            return total;
        }

        private void docPlataDetaliuDGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            Boolean modificat = false;
            if (e.ColumnIndex == ValoareColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    val = Convert.ToDecimal(e.FormattedValue,Application.CurrentCulture.NumberFormat);
                }
                catch { }
                
                if (docPlataDetaliuDGV[nrDataDocColumn.Index, e.RowIndex].Value != DBNull.Value &&
                    Math.Abs(val) > Math.Abs(Convert.ToDecimal(docPlataDetaliuDGV[restColumn.Index, e.RowIndex].Value)))
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Valoarea platită trebuie să fie mai mică sau egală cu restul de plata!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    e.Cancel = true;
                    return;
                }
                if ((docPlataDetaliuDGV[ValoareColumn.Index, e.RowIndex].Value == DBNull.Value) || (Convert.ToDecimal(docPlataDetaliuDGV[ValoareColumn.Index, e.RowIndex].Value) != val))
                {
                    docPlataDetaliuDGV[ValoareColumn.Index, e.RowIndex].Value = val;
                    Decimal valTVADoc = Convert.ToDecimal(docPlataDetaliuDGV[TVADocumentColumn.Index, e.RowIndex].Value);
                    Decimal valTot = Convert.ToDecimal(docPlataDetaliuDGV[sumaColumn.Index, e.RowIndex].Value);
                    if(valTot!=Decimal.Zero)
                        docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = val*valTVADoc/valTot;
                    else
                        docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = val * Convert.ToDecimal(Convert.ToDouble(FSRow.CotaTVAImplicita)/100.00);
                    ///nu trebuie sa depaseasca restul de plata TVA
                    if (Convert.ToDecimal(docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value) > Convert.ToDecimal(docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value))
                        docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value;
                    modificat = true;
                }
            }
            if (e.ColumnIndex == ValoareTVAColumn.Index)
            {
                Decimal val = Decimal.Zero;
                try
                {
                    val = Convert.ToDecimal(e.FormattedValue, Application.CurrentCulture.NumberFormat);
                }
                catch { }

                if (docPlataDetaliuDGV[nrDataDocColumn.Index, e.RowIndex].Value != DBNull.Value &&
                    Math.Abs(val) > Math.Abs(Convert.ToDecimal(docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value)))
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Valoarea TVA platită(încasată) trebuie să fie mai mică sau egală cu TVA rest de plată(încasare)!", String.Empty,MessageBoxFrm.ImaginiMB.InformareIcon, null);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    e.Cancel = true;
                    return;
                }

                if (docPlataDetaliuDGV[nrDataDocColumn.Index, e.RowIndex].Value != DBNull.Value &&
                    Math.Abs(val) > Math.Abs(Convert.ToDecimal(docPlataDetaliuDGV[ValoareColumn.Index, e.RowIndex].Value)))
                {
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare validare", "Valoarea TVA platită(încasată) trebuie să fie mai mică sau egală cu restul de plată(încasare)!", String.Empty,MessageBoxFrm.ImaginiMB.InformareIcon, null);
                    mbt.AddButton("Ieşire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    e.Cancel = true;
                    return;
                }

                if ((docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value == DBNull.Value) ||
                    (Convert.ToDecimal(docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value) != val))
                {
                    docPlataDetaliuDGV[ValoareTVAColumn.Index, e.RowIndex].Value = val;
                    modificat = true;
                }
            }
            if (modificat == true)
                SeteazaTotalDocument();

            if (e.ColumnIndex == nrDataDocColumn.Index)
            {
                ComboBox cbb = docPlataDetaliuDGV.EditingControl as ComboBox;
                if (cbb != null && cbb.SelectedItem!=null)
                {
                    ESRPDataSetPlati.fares_GenereazaDocumentePentruPlataRow gppd = ((DataRowView)cbb.SelectedItem).Row as
                        ESRPDataSetPlati.fares_GenereazaDocumentePentruPlataRow;
                    docPlataDetaliuDGV[sumaColumn.Index, e.RowIndex].Value = gppd.Total;
                    docPlataDetaliuDGV[achitatColumn.Index, e.RowIndex].Value = gppd.Achitat;
                    docPlataDetaliuDGV[restColumn.Index, e.RowIndex].Value = gppd.RestPlata;
                    docPlataDetaliuDGV[TVADocumentColumn.Index, e.RowIndex].Value = gppd.TotalValoareTVA;
                    docPlataDetaliuDGV[AchitatTVAColumn.Index, e.RowIndex].Value = gppd.AchitatTVA;
                    docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value = gppd.RestPlataTVA;

                }
            }
            
        }

        private void docPlataDetaliuDGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == nrDataDocColumn.Index)
            {
                int poz = 0;
                ESRPDataSetPlati.fares_GenereazaDocumentePentruPlataRow gppd = null;
                if (DocGenPtPlataSearch.Current != null)
                {
                    gppd = ((DataRowView)DocGenPtPlataSearch.Current).Row as ESRPDataSetPlati.fares_GenereazaDocumentePentruPlataRow;
                    if (gppd.IsIDDocumentNull())
                    {
                        if(docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value!=DBNull.Value)
                        {
                            poz = DocGenPtPlataSearch.Find("IDDocument", docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value);
                            if(poz!=-1)
                                DocGenPtPlataSearch.Position = poz;
                        }
                    }
                    else
                        if (docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value == DBNull.Value)
                        {
                            poz = DocGenPtPlataSearch.Find("IDDocument", docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value);
                            if(poz!=-1)
                                DocGenPtPlataSearch.Position = poz;
                        }
                        else
                            if (Convert.ToInt64(docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value) != gppd.IDDocument)
                            {
                                poz = DocGenPtPlataSearch.Find("IDDocument", docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value);
                                if (poz!=-1)
                                    DocGenPtPlataSearch.Position = poz;
                            }
                }
                else
                {
                    if (docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value != DBNull.Value)
                    {
                        if (DocGenPtPlataSearch.SupportsSearching)
                        {
                            poz = DocGenPtPlataSearch.Find("IDDocument", docPlataDetaliuDGV[e.ColumnIndex, e.RowIndex].Value);
                            if (poz!=-1)
                                DocGenPtPlataSearch.Position = poz;
                        }
                    }
                }
                if (poz >= 0 )
                {
                    if (DocGenPtPlataSearch.Current == null)
                        return;
                    gppd = ((DataRowView)DocGenPtPlataSearch.Current).Row as ESRPDataSetPlati.fares_GenereazaDocumentePentruPlataRow;
                    if (docPlataDetaliuDGV[sumaColumn.Index, e.RowIndex].Value==null || Convert.ToDecimal(docPlataDetaliuDGV[sumaColumn.Index, e.RowIndex].Value) != gppd.Total)
                        docPlataDetaliuDGV[sumaColumn.Index, e.RowIndex].Value = gppd.Total;
                    if (docPlataDetaliuDGV[achitatColumn.Index, e.RowIndex].Value==null || Convert.ToDecimal(docPlataDetaliuDGV[achitatColumn.Index, e.RowIndex].Value) != gppd.Achitat)
                        docPlataDetaliuDGV[achitatColumn.Index, e.RowIndex].Value = gppd.Achitat;
                    if (docPlataDetaliuDGV[restColumn.Index, e.RowIndex].Value==null || Convert.ToDecimal(docPlataDetaliuDGV[restColumn.Index, e.RowIndex].Value) != gppd.RestPlata)
                        docPlataDetaliuDGV[restColumn.Index, e.RowIndex].Value = gppd.RestPlata;

                    ///TVA la incasare
                    if (docPlataDetaliuDGV[TVADocumentColumn.Index, e.RowIndex].Value == null || Convert.ToDecimal(docPlataDetaliuDGV[TVADocumentColumn.Index, e.RowIndex].Value) != gppd.TotalValoareTVA)
                        docPlataDetaliuDGV[TVADocumentColumn.Index, e.RowIndex].Value = gppd.TotalValoareTVA;
                    if (docPlataDetaliuDGV[AchitatTVAColumn.Index, e.RowIndex].Value == null || Convert.ToDecimal(docPlataDetaliuDGV[AchitatTVAColumn.Index, e.RowIndex].Value) != gppd.AchitatTVA)
                        docPlataDetaliuDGV[AchitatTVAColumn.Index, e.RowIndex].Value = gppd.AchitatTVA;
                    if (docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value == null || Convert.ToDecimal(docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value) != gppd.RestPlataTVA)
                        docPlataDetaliuDGV[RestPlataTVAColumn.Index, e.RowIndex].Value = gppd.RestPlataTVA;



                }
            }
        }

        private void documentePlataDetaliuBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            //tipul operatiunii nu se poate schimba dupa salvare
            if (documentePlataBindingSource.Current!=null)
                tipOperatiuneCB.Enabled = ((DataRowView)documentePlataBindingSource.Current).IsNew;
        }

        override public void Cauta(object sender, EventArgs e)
        {
            EnableMainSearchButton = false;
            PlatiSearchFrm frm = new PlatiSearchFrm(ModuleInfo,ParteneriProprii);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                documentePlataBindingSource.Filter = frm.Filtru;
                /*documentePlataTableAdapter.Connection = DeschideConexiune(workConnString);
                documentePlataTableAdapter.FillByFiltru(esrpDataSetPlati.DocumentePlata, frm.Filtru);
                InchideConexiune(documentePlataTableAdapter.Connection);*/
                tipOperatiuneCB_SelectedIndexChanged(sender, e);

            }
            EnableMainBrowseButton = true;
            EnableMainSearchButton = true;
        }

        private void Facturi(object sender, EventArgs e)
        {
            ESRPDataSetPlati.fares_ParteneriCUIRow parr = ((DataRowView)denumireCB.SelectedItem).Row as ESRPDataSetPlati.fares_ParteneriCUIRow;
            if (parr != null)
            {
                SqlConnection con = DeschideConexiune(workConnString);
                fares_GenereazaDocumentePentruPlataTableAdapter.Connection = con;
                fares_GenereazaDocumentePentruPlataTableAdapter.Fill(esrpDataSetPlati.fares_GenereazaDocumentePentruPlata,
                    ModuleInfo.CodUnitate, parr.IDPartener, tipOperatiuneCB.SelectedValue.ToString(), -1, ModuleInfo.AnArhiva);
                InchideConexiune(con);
            }
            ListafacturiFrm frm = new ListafacturiFrm(ModuleInfo,esrpDataSetPlati.fares_GenereazaDocumentePentruPlata);
            //frm.MdiParent = this.MdiParent;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (docPlataDetaliuDGV.SelectedRows.Count == 0)
                {
                    if (docPlataDetaliuDGV.RowCount == 0)
                        return;
                    docPlataDetaliuDGV.Rows[0].Selected = true;
                }
                docPlataDetaliuDGV.SelectedRows[0].Cells[nrDataDocColumn.Index].Selected = true;
                DataGridViewComboBoxCell cb = docPlataDetaliuDGV.SelectedRows[0].Cells[nrDataDocColumn.Index] as DataGridViewComboBoxCell;

                if (cb.IsInEditMode)
                {
                    ComboBox cbb = docPlataDetaliuDGV.EditingControl as ComboBox;
                    cbb.SelectedValue = frm.selectedDataRow["IDDocument"];
                }
                else
                    cb.Value = frm.selectedDataRow["IDDocument"];
                this.ActiveControl = docPlataDetaliuDGV;
            }
        }

        private void numarTB_TextChanged(object sender, EventArgs e)
        {
            //NumberToWordsConverter nc = new NumberToWordsConverter();
            //if (numarTB.Text!=String.Empty)
            //    labelNumber.Text=nc.NumberToWords(Convert.ToInt32(numarTB.Text));
        }
        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();
        private void Tiparire(object sender, EventArgs e)
        {
            Salvare(this, null);
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(workConnString));

            DataRowView dr = (DataRowView)documentePlataBindingSource.Current;
            if (dr == null || dr.IsNew)
                return;
            ESRPDataSetPlati.DocumentePlataRow ddr = dr.Row as ESRPDataSetPlati.DocumentePlataRow;

            ESRPDataSetPlati eSRPDS = new ESRPDataSetPlati();
            Cursor.Current = Cursors.AppStarting;
            String linia1 = String.Empty, linia2 = String.Empty;



            PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);
            //esrpDataSetPlati - este data setul cu care lucram

      
            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();
            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS, "BalconSetup"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [BalconSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;
            listTA[0].Fill(eSRPDS.BalconSetup);

            listTA.Add(new SqlDataAdapter("SELECT * FROM [FaresSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[1].SelectCommand.CommandType = CommandType.Text;
            listTA[1].Fill(eSRPDS.FaresSetup);
            listBS.Add(new BindingSource(eSRPDS, "FaresSetup"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [DocumentePlata] WHERE IDDocumentPlata =" + ddr.IDDocumentPlata, cmd.Connection));
            listTA[2].SelectCommand.CommandType = CommandType.Text;
            listTA[2].Fill(eSRPDS.DocumentePlata);
            listBS.Add(new BindingSource(eSRPDS, "DocumentePlata"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewDetaliuPlata] WHERE IDDocumentPlata =" + ddr.IDDocumentPlata.ToString(), cmd.Connection));
            listTA[3].SelectCommand.CommandType = CommandType.Text;
            listTA[3].Fill(eSRPDS.fares_viewDetaliuPlata);
            listBS.Add(new BindingSource(eSRPDS, "fares_viewDetaliuPlata"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_ViewParteneri] WHERE IDPartener =" + ddr.IDPartener.ToString(), cmd.Connection));
            listTA[4].SelectCommand.CommandType = CommandType.Text;
            listTA[4].Fill(eSRPDS.fares_ViewParteneri);
            listBS.Add(new BindingSource(eSRPDS, "fares_ViewParteneri"));

            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewUnitati] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            listTA[5].SelectCommand.CommandType = CommandType.Text;
            listTA[5].Fill(eSRPDS.fares_viewUnitati);
            listBS.Add(new BindingSource(eSRPDS, "fares_viewUnitati"));

            String reprezentandStr = String.Empty;
            for (int i = 0; i < listBS[3].Count; i++)
            { 
                ESRPDataSetPlati.fares_viewDetaliuPlataRow rd = ((DataRowView)listBS[3].Current).Row as ESRPDataSetPlati.fares_viewDetaliuPlataRow;
                if(reprezentandStr!=String.Empty)
                    reprezentandStr+= ",";
                if (rd.IsNrDocNull() || rd.IsDataDocNull())
                {
                    reprezentandStr = "AVANS";
                }
                else
                    reprezentandStr += rd.NrDoc.ToString() + "/" + rd.DataDoc.ToShortDateString();
            }

            //String[] nume = new String[50], functii = new String[50];
            //for (int i = 0; i < 50; i++)
            //{
            //    nume[i] = String.Empty;
            //    functii[i] = String.Empty;
            //}
            //for (int i = 0; i < Math.Min(listBS[6].Count, 50); i++)
            //{
            //    listBS[6].Position = i;
            //    nume[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Nume"].ToString();
            //    functii[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Functia"].ToString();

            //}


            InchideConexiune(cmd.Connection);


            //String artAl = artAlCB.Text.Substring(0, 2);
            //String diviziune = JurnalCB.Text + "." + GetTitlu(artAl) + "." + artAlCB.Text;

            if (ddr.IDTipPlata == 5)
            {
                MessageBoxFrm mbt = new MessageBoxFrm("Selectie", "Acum aveti posibilitatea de a alege cate exemplare din chitanta se vor tiparii pe o foaie.", "Modalitatea de tiparire?", MessageBoxFrm.ImaginiMB.IntrebareIcon, null);
                mbt.AddButton("1/pagina", 70, mbt.MessageBoxFrm_Click_Yes);
                mbt.AddButton("2/pagina", 70, mbt.MessageBoxFrm_Click_No);
                DialogResult retD = mbt.ShowDialog();
                frm.NumeRaport = "Chitanta.rdlc";
                if (retD == DialogResult.No)
                    frm.NumeRaport = "ChitantaDoi.rdlc";

            }
            else
                return;


            frm.AddDataSource("ESRPDataSet_FaresSetup", listBS[1]);
            frm.AddDataSource("ESRPDataSet_BalconSetup", listBS[0]);
            frm.AddDataSource("ESRPDataSet_DocumentePlata", listBS[2]);
            frm.AddDataSource("ESRPDataSet_fares_viewDetaliuPlata", listBS[3]);
            frm.AddDataSource("ESRPDataSet_fares_ViewParteneri", listBS[4]);
            //frm.AddDataSource("ESRPDataSet_aspnet_Users", listBS[5]);
            //frm.AddDataSource("ESRPDataSet_Semnaturi", listBS[6]);      
            frm.AddDataSource("ESRPDataSet_Unitati", listBS[5]);

            frm.SetWindowFormat(true);



            foreach (SqlDataAdapter da in listTA)
                if (da != null) da.Dispose();
            listTA.Clear();
            InchideConexiune(cmd.Connection);
            frm.MdiParent = this.MdiParent;

            NumberToWordsConverter nc = new NumberToWordsConverter();
            frm.AddParameter("Adica", nc.NumberToWords(ddr.ValoareTotala), true);
            frm.AddParameter("Reprezentand", reprezentandStr, true);
            //frm.AddParameter("Functii", functii, true);

            frm.Show();
            cmd.Dispose();



            Cursor.Current = Cursors.Default;
        }

    }


    [Serializable]
    public class TipOperatiunePlata
    {
        public TipOperatiunePlata(String nume, String tag)
        {
            _Name = nume;
            _Tag = tag;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private String _Tag = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Tag
        {
            get
            {
                return _Tag;
            }
            set
            {
                _Tag = value;
            }
        }
    }

    public class DocumentePlataTableAdapterEx : DataSets.ESRPDataSetPlatiTableAdapters.DocumentePlataTableAdapter
    {
        public DocumentePlataTableAdapterEx()
            : base()
        {

        }
        public void SetTableName(String an)
        {
            foreach (SqlCommand cmd in this.CommandCollection)
            {
                if (cmd.CommandText.Contains("dbo.DocumentePlata"))
                    cmd.CommandText = cmd.CommandText.Replace("FROM dbo.DocumentePlata", "FROM [DocumentePlata" + an + "]");
                else
                    cmd.CommandText = cmd.CommandText.Replace("FROM DocumentePlata", "FROM [DocumentePlata" + an + "]");
            }
        }


    }

    public class DocumentePlataDetaliuTableAdapterEx : DataSets.ESRPDataSetPlatiTableAdapters.DocumentePlataDetaliuTableAdapter
    {
        public DocumentePlataDetaliuTableAdapterEx()
            : base()
        {

        }
        public void SetTableName(String an)
        {
            foreach (SqlCommand cmd in this.CommandCollection)
            {
                if (cmd.CommandText.Contains("dbo.DocumentePlataDetaliu"))
                    cmd.CommandText = cmd.CommandText.Replace("FROM dbo.DocumentePlataDetaliu", "FROM [DocumentePlataDetaliu" + an + "]");
                else
                    cmd.CommandText = cmd.CommandText.Replace("FROM DocumentePlataDetaliu", "FROM [DocumentePlataDetaliu" + an + "]");
            }
        }
    }

    class NumberToWordsConverter
    {
        // Single-digit and small number names
        private string[] _smallNumbers = new string[] { "zero", "unu", "doi", "trei", "patru", "cinci", "sase", "sapte", "opt", "noua", "zece",
            "unsprezece", "doisprezece", "treisprezece", "patrusprezece", "cincisprezece", "saisprezece", "saptesprezece", "optsprezece", "nouasprezece" };

        // Tens number names from twenty upwards
        private string[] _tens = new string[] { "", "", "douazeci", "treizeci", "patruzeci", "cincizeci", "saizeci", "saptezeci", "optzeci", "nouazeci" };

        // Scale number names for use during recombination
        private string[] _scaleNumbers = new string[] { "", "mii", "milioane", "bilioane"};



        public string NumberToWords(Decimal number)
        {
            return NumberToWords(Convert.ToInt32(Decimal.Floor(number))) + " lei si " + NumberToWords(Convert.ToInt32((number*100)%100)) + " bani";
        }
        // Converts an integer value into English words
        public string NumberToWords(int number)
        {
            // Zero rule
            if (number == 0)
                return _smallNumbers[0];

            // Array to hold four three-digit groups
            int[] digitGroups = new int[4];

            // Ensure a positive number to extract from
            int positive = Math.Abs(number);

            // Extract the three-digit groups
            for (int i = 0; i < 4; i++)
            {
                digitGroups[i] = positive % 1000;
                positive /= 1000;
            }

            // Convert each three-digit group to words
            string[] groupText = new string[4];

            for (int i = 0; i < 4; i++)
                groupText[i] = ThreeDigitGroupToWords(digitGroups[i]);

            // Recombine the three-digit groups
            string combined = groupText[0];
            bool appendAnd;

            // Determine whether an 'and' is needed
            appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100);

            // Process the remaining groups in turn, smallest to largest
            for (int i = 1; i < 4; i++)
            {
                // Only add non-zero items
                if (digitGroups[i] != 0)
                {
                    // Build the string to add as a prefix
                    string prefix = groupText[i] + " " + _scaleNumbers[i];

                    if (combined.Length != 0)
                        prefix += appendAnd ? " si " : ", ";

                    // Opportunity to add 'and' is ended
                    appendAnd = false;

                    // Add the three-digit group to the combined string
                    combined = prefix + combined;
                }
            }

            // Negative rule
            if (number < 0)
                combined = "Negativ " + combined;

            return combined;
        }



        // Converts a three-digit group into English words
        private string ThreeDigitGroupToWords(int threeDigits)
        {
            // Initialise the return text
            string groupText = "";

            // Determine the hundreds and the remainder
            int hundreds = threeDigits / 100;
            int tensUnits = threeDigits % 100;

            // Hundreds rules
            if (hundreds != 0)
            {
                groupText += _smallNumbers[hundreds] + " sute";

                if (tensUnits != 0)
                    groupText += " ";
            }

            // Determine the tens and units
            int tens = tensUnits / 10;
            int units = tensUnits % 10;

            // Tens rules
            if (tens >= 2)
            {
                groupText += _tens[tens];
                if (units != 0)
                    groupText += " si " + _smallNumbers[units];
            }
            else if (tensUnits != 0)
                groupText += _smallNumbers[tensUnits];

            return groupText;
        }
    }
}
